package com.example.apigateway.Interceptor;

import com.example.apigateway.common.CommonConstant;
import com.example.apigateway.common.UserContext;
import com.example.apigateway.dao.UserDao;
import com.example.apigateway.model.User;
import com.google.common.base.Joiner;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-06-28
 **/
@Component
public class AuthInterceptor implements HandlerInterceptor {

    private static final String TOKEN_COOKIE = "token";

    @Autowired
    private UserDao userDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,String[]> map = request.getParameterMap();
        map.forEach((k,v)->request.setAttribute(k, Joiner.on(",").join(v)));
        String requestURI = request.getRequestURI();
        if (requestURI.startsWith("/static") || requestURI.startsWith("/error")) {
            return true;
        }
        Cookie cookie = WebUtils.getCookie(request,TOKEN_COOKIE);
        if(cookie!=null && StringUtils.isNotBlank(cookie.getValue())) {
            User user = userDao.getUserByToken(cookie.getValue());
            if(user!=null) {
                request.setAttribute(CommonConstant.LOGIN_USER_ATTRIBUTE,user);
                UserContext.setUser(user);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        String requestURI = request.getRequestURI();
        if (requestURI.startsWith("/static") || requestURI.startsWith("/error")) {
            return ;
        }
        User user = UserContext.getUser();
        if(user!=null && StringUtils.isNotBlank(user.getToken())) {
            String token = requestURI.startsWith("logout")?"":user.getToken();
            Cookie cookie = new Cookie(TOKEN_COOKIE,token);
            cookie.setPath("/");
            cookie.setHttpOnly(false);
            response.addCookie(cookie);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        UserContext.remove();
    }
}


